package widget.progress;

import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;

import static widget.progress.ProgressInterface.MAX_LEVEL;


/**
 * Created by Mr.Fan on 2015/8/20.
 */
public class ProgressLayerDrawable extends LayerDrawable implements Runnable, Animatable {

    private float stepPercent = 0.01f;
    private int duration = 300;
    private float slowlyPercent = 0.95f;
    private boolean isAnimateRunning = false;
    private boolean isFastComplete = false;

    /**
     * Create a new layer drawable with the list of specified layers.
     *
     * @param layers A list of drawables to use as layers in this new drawable.
     */
    public ProgressLayerDrawable(Drawable[] layers) {
        super(layers);
        setCallback(this);
    }

    @Override
    public void run() {
        isAnimateRunning = true;
        if (getLevel() < MAX_LEVEL) {
            final int slowlyLevel = (int) (MAX_LEVEL * slowlyPercent);
            if (!isFastComplete && getLevel() >= slowlyLevel) {
                stop();
                return;
            }
            int dur = isFastComplete ? 5 : duration;
            int nextlevel = getLevel() + (int) (MAX_LEVEL * stepPercent) * (isFastComplete ? 5 : 1);
            nextlevel = nextlevel > MAX_LEVEL ? MAX_LEVEL : nextlevel;
            setLevel(nextlevel);
            invalidateSelf();
            scheduleSelf(this, SystemClock.uptimeMillis() + dur);
        } else {
            stop();
        }
    }

    @Override
    public void start() {
        if (!isRunning()) {
            isAnimateRunning = true;
            isFastComplete = false;
            if (getLevel() >= MAX_LEVEL)
                setLevel(0);
            scheduleSelf(this, SystemClock.uptimeMillis() + duration);
        }
    }

    @Override
    public void stop() {
        if (isRunning()) {
            unscheduleSelf(this);
            isAnimateRunning = false;
            isFastComplete = false;
        }
    }

    @Override
    public boolean isRunning() {
        return isAnimateRunning;
    }

    /**
     * 设置不确定进度条的动画时间
     *
     * @param duration
     */
    public void setDuration(int duration) {
        if (duration > 0)
            this.duration = duration;
    }

    public void setCompleted() {
        stop();
        isFastComplete = true;
        run();
    }
}
